package com.bsh.utils.system;

import com.bsh.utils.SimpleCache;
import com.bsh.utils.system.smsApi.ISmsApi;
import com.bsh.utils.system.smsApi.SmsApiCF;
import com.bsh.utils.system.smsApi.SmsApiYp;

/**
 * 触发短信
 * 
 * @author gsh
 *    	SmsReponseMessage msg = SmsUtil.sendValidCode("13120660747","1234");
 */
public class SmsUtil {
	private static SimpleCache<Integer> cache = new SimpleCache<Integer>(1800);

	static ISmsApi[] smsApi = null;

	static void init() {
		if (smsApi == null) {
			smsApi = new ISmsApi[2];
			smsApi[0] = new SmsApiYp();
			smsApi[1] = new SmsApiCF();
		}
	}
	static{
		init();
	}

	/**
	 * 发送验证码
	 *
	 */
	public static synchronized SmsReponseMessage sendValidCode(String mobile, String validCode) {
		String key = String.format("sms_valid_code_%s", mobile);
		Integer val = cache.Get(key,Integer.class);
		SmsReponseMessage msg = null;
		ISmsApi api;
		if (val!=null && val == 0) {
			api = smsApi[1];
			cache.Put(key, 1);
			System.out.println("通道1发送短信___手机:"+mobile+"___验证码："+validCode);
		} else {
			api = smsApi[0];
			cache.Put(key, 0);
			System.out.println("通道2发送短信___手机:"+mobile+"___验证码："+validCode);
		}		
		msg = api.sendValidCode(mobile, validCode);
		return msg;
	}

}
